/**
 * 
 */
package com.fnic.pearl.scheduler.mod;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.fnic.pearl.scheduler.constant.CondHeaderField;
import com.fnic.pearl.scheduler.dao.SchedulerStore;
import com.fnic.pearl.scheduler.model.HeartBeatResp;
import com.fnic.pearl.scheduler.model.ProbeStatus;
import com.fnic.pearl.scheduler.model.SessionKey;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

/**
 * 对探针的 SessionKey 进行管理
 * 
 * @author HuHaiyang
 * @date 2013年11月14日
 */
public class ProbeSessionKeyManager
{
    private Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
    private static ProbeSessionKeyManager instance = new ProbeSessionKeyManager();
    public static ProbeSessionKeyManager getInstance()
    {
        return instance;
    }
    
    // 存放所有待通知给探针的 session key
    private Map<Integer,SessionKey> wissueSessionKeys = new HashMap<Integer, SessionKey>();
    
    public synchronized SessionKey getWissue(int probeId)
    {
        return wissueSessionKeys.get(probeId);
    }
    
    // 放置待通知给指定探针的 session key
    // 同时，在此处设置该探针的最新 session key 和 上一次 session key
    public synchronized void putWissue(int probeId, SessionKey sessionKey)
    {
        wissueSessionKeys.put(probeId, sessionKey);
        HeartBeatResp hbr = new HeartBeatResp(
                CondHeaderField.HB_BTYPE_SESSION_KEY, gson.toJson(sessionKey));
        SchedulerStore.getInstance().pushHbResp(probeId, hbr);
        
        ProbeStatus ps = ProbeStatusManager.getInstance().get(probeId);
        if (ps != null)
        {
            SessionKey prevSessionKey = ps.getSessionKey();
            if (prevSessionKey != null && sessionKey != null)
            {
                sessionKey.setPrevCreateTime(prevSessionKey.getCreateTime());
                sessionKey.setPrevSessionKey(prevSessionKey.getSessionKey());
            }
            sessionKey.setCreateTime(new Date());
            ps.setSessionKey(sessionKey);
        }
    }
}
